<?php
Class SP_Routing_Router
{
	private $module;
	private $action;
	private $vars = array();
	private $uri_array;
	private $uri;
	private $root_page = false;

	public function getModule()
	{
		return $this->vars['module'];
	}

	public function getAction()
	{
		return $this->vars['action'];
	}

	public function getVars()
	{
		return $this->vars;
	}

	//возвращает uri переданную серверу
	public function getUri()
	{
		if ( empty($this->uri) ) $this->uri=getenv('REQUEST_URI');
		return $this->uri;
	}

	public function isRootPage()
	{
		return $this->root_page;
	}

	//устанавливает uri вручную
	public function setUri($uri)
	{
		$this->uri=$uri;
	}

	//возвращает массив распарсенной uri
	public function getUriArray()
	{
		if (!$this->uri_array) $this->uri_array=SP_Common_Functions::splitSlashes($this->getUri());
		if(preg_match("/.php/i", $this->uri_array[0])) //определяет было ли передано имя скрипта
		{
			$this->uri_array=array_slice($this->uri_array,1);
		}
		//$this->uri_array=$array;
		return $this->uri_array;
	}

	//устанавливает массив uri вручную
	public function setUriArray($uri_array)
	{
		if(is_array($uri_array)) $this->uri_array=$uri_array;
	}

	public function defineRoute()
	{
		foreach(SP_Routing_RouteCollector::getAll() as $name => $route)
		{
			if ($this->compareUriRoute($route)) return $name;
		}
		return false;
	}
	
	public function compareUriRoute($route)
	{
		$uri_array=$this->getUriArray();
		$route_array=$route->getUriArray();
		if(count($uri_array) == 0) $this->root_page=true;
		//count($uri_array) > count($route_array)
		if( end($route_array) == '*' or count($uri_array) == count($route_array) )
		{
			foreach($uri_array as $key => $uri_element)
			{
				$route_element=$route_array[$key];
				//echo "uri '$uri_element' === route '$route_element'<br />";
				if($route_element != '*')
				{
					//var_dump($uri_array);
					// проверяем есть ли в элементе маршрута символ :
					if(strpos($route_element,':') === false)
					{
						if($route_element != $uri_element) return false;
					}
					else
					{
						$route_element=substr($route_element, 1);
						//валидация значений из uri 
						if(!$route->validate($route_element,$uri_element)) return false;
						$this->vars[$route_element]=$uri_element;
					}
				}
				else
				{
					$mas=array_slice($uri_array, $key);
					
					//$this->vars=array_merge($this->vars,$mas);
					$mas=SP_Common_Functions::arrayToAssocArray($mas);
					//var_dump($mas);
					$this->vars=array_merge($this->vars,$mas);
					break;
				}
			}
			if(empty($this->vars['module'])) $this->vars['module']=$route->getModule();
			if(empty($this->vars['action'])) $this->vars['action']=$route->getAction();
			//var_dump($this->vars);
			return true;
			
		}
		return false;
	}
	
	public function generateUriFromRoute($route,$params=array())
	{
		$route_array=$route->getUriArray();
		//var_dump($route_array);
		$url_params_count=0;
		$uri='/';
		foreach($route_array as $route_element)
		{
			$uri_element=$route_element;
			if(strpos($route_element,':') !== false)
			{
				$param_name=substr($route_element, 1);
				if( empty($params[$param_name]) ) throw new exception('Not found parameter "'.$param_name.'" to generate uri "'.$route->getUri().'"');
				$uri_element=$params[$param_name];
				$url_params_count++;
			}
			$uri.=$uri_element.'/';
		}
		if( $url_params_count > count($params) ) throw new exception('Not enough parameters to generate uri "'.$route->getUri().'"');
		if( substr($uri,-2) == '*/' ) $uri=SP_Common_Functions::delLastChar($uri,2);
		if( strlen($uri)>1 ) $uri=SP_Common_Functions::delLastChar($uri);
		return $uri;
	}


}